<template>
  <div
    style="border:1px solid #cccccc; border-radius: 8px; width: 500px; height: 350px; background-color: #d6eff7"
    v-loading="loading"
  >
    <h1>用户登录</h1>

    <el-form :model="user" :rules="rules" ref="user" label-width="180px">
      <el-form-item label="用户名/手机号码" prop="ID">
        <el-input v-model="user.ID"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="user.password" @keyup.enter.native="submitForm('user')"></el-input>
      </el-form-item>

      <div style="height: 20px;"></div>

      <el-button type="primary" plain @click="change()">注册</el-button>
      <el-button @click="resetForm('user')">重置</el-button>
      <el-button type="primary" @click="submitForm('user')">登录</el-button>
    </el-form>

    <br />
    <el-button type="warning" @click="toStoreLogin()" size="mini">商家登录/注册</el-button>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      loading: false,
      user: {
        ID: "",
        password: "",
      },
      rules: {
        ID: [
          { required: true, message: "请输入用户名/手机号码", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    change() {
      this.$emit("toRegister");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //   alert("submit!");
          var url = process.env.URL_HEAD + "/touser/user/user/login";

          this.loading = true;
          this.$http
            .get(url, {
              params: { ID: this.user.ID, password: this.user.password },
              withCredentials: true,
            })
            .then(
              (response) => {
                // console.log(response);

                if (response.data.status == "ok") {
                  console.log("登录成功！");

                  this.$refs["user"].resetFields();
                  this.$emit("loginSuccess");
                } else {
                  this.$message.error("登录失败，请检查账号和密码");
                }

                this.loading = false;
              },
              (response) => {
                this.$message.error("系统异常，请重试");
                
                this.loading = false;
              }
            );
        } else {
          this.$message.error("请输入账号和密码");
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    toStoreLogin() {
      window.location.href = process.env.STORE_LOGIN_URL;
    },
  },
};
</script>

<style scoped>
.h1 {
  font-size: 50px;
}
.el-input {
  width: 200px;
}
</style>
